package com.xbn.netty.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author XBN
 * @date 2020/10/16 12:56
 * @email 78742541@qq.com
 */
public class GroupChatClientCopy {
    //定义相关的属性
    private final String HOST="127.0.0.1";//服务器ip
    private final int PORT=6667;//服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;
    //构造器
    public GroupChatClientCopy() throws IOException {
       selector= Selector.open();
            //连接服务器
        socketChannel= socketChannel.open(new InetSocketAddress(HOST,PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username+"is ok,您已经成功连接上服务器");
    }

    //向服务器发送消息
    public void sendInfo(String info)
    {
        info=username+"说:"+info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }
    //读取服务器端回复的消息
    public void readInfo(){
        try {
            int readChannels = selector.select();
            if(readChannels>0)
            {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext())
                {
                    SelectionKey key = iterator.next();
                    if(key.isReadable())
                    {
                        //得到相关的通道
                        SocketChannel sc = (SocketChannel) key.channel();
                        //得到一个buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                    //删除当前的selectKey，防止重复操作
                    iterator.remove();
                }
            }
            else {
             //   System.out.println("没有可用的通道....");
            }
        }catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        //启动客户端
        GroupChatClientCopy chatClient = new GroupChatClientCopy();
        //启动一个线程
        new Thread()
        {
            public void run(){
                while (true)
                {
                        //每三秒读取一次数据
                    chatClient.readInfo();
                    try {
                        Thread.sleep(3000);
                    }catch (InterruptedException e)
                    {
                        e.printStackTrace();
                    }
                }
            }
        }.start();
        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()){
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
